package com.yihubang.taobaokotlin.ui.fragment

import android.view.View
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.yihubang.taobaokotlin.R
import com.yihubang.taobaokotlin.ui.adapter.HomePagerAdapter
import com.yihubang.taobaokotlin.base.BaseFragment
import com.yihubang.taobaokotlin.interfaces.IHomeCallback
import com.yihubang.taobaokotlin.model.Categories
import com.yihubang.taobaokotlin.presenter.impl.HomePresenterImpl

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/5/10.
 * PS: Not easy to write code, please indicate.
 */
class HomeFragment : BaseFragment(), IHomeCallback {

    private lateinit var homePagerAdapter: HomePagerAdapter

    override fun getRootViewResId(): Int {
        return R.layout.fragment_home
    }

    override fun initView(rootView: View) {

        val mTabLayout: TabLayout = rootView.findViewById(R.id.home_indicator)
        val homePager: ViewPager = rootView.findViewById(R.id.home_pager)

        //TabLayout绑定ViewPager
        mTabLayout.setupWithViewPager(homePager)
        //给ViewPager设置适配器
        homePagerAdapter = HomePagerAdapter(childFragmentManager)
        //设置适配器
        homePager.adapter = homePagerAdapter
    }

    override fun initPresenter() {
        HomePresenterImpl.registerViewCallback(this)
        HomePresenterImpl.getCategories()
    }

    override fun release() {
        super.release()
        HomePresenterImpl.unregisterViewCallback(this)
    }

    override fun onCategoriesLoaded(category: Categories?) {
        //加载数据成功的页面
        setUpState(State.SUCCESS)
        homePagerAdapter.setCategories(category)
    }

    override fun onError() {
        setUpState(State.ERROR)
    }

    override fun onLoading() {
        setUpState(State.LOADING)
    }

    override fun onEmpty() {
        setUpState(State.EMPTY)
    }
}